<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改出售记录')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:insert="include :: select2-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-record-edit" th:object="${csSalesRecord}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">购买账户：</label>
                <div class="col-sm-8">
                    <div class="input-group" style="width: 100%">
                        <select name="account" id="account" class="form-control m-b">
                            <option value="1">账户1</option>
                            <option value="2">账户2</option>
                            <option value="3">账户3</option>
                            <option value="4">账户4</option>
                            <option value="5">账户5</option>
                            <option value="6">账户6</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">物品名称：</label>
                <div class="col-sm-8">
                    <div class="input-group" style="width: 100%">
                        <input type="hidden" id="initialNameValue" th:value="${csSalesRecord.name}">
                        <input type="hidden" id="initialMarketHashNameValue" th:value="${csSalesRecord.marketHashName}">
                        <select name="marketHashName" id="marketHashName" class="form-control m-b"
                                th:field="*{marketHashName}">
                            <option value=""></option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售价格：</label>
                <div class="col-sm-8">
                    <input name="sellPrice" th:field="*{sellPrice}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售时单个成本均价：</label>
                <div class="col-sm-8">
                    <input name="sellCostPrice" th:field="*{sellCostPrice}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出售数量：</label>
                <div class="col-sm-8">
                    <input name="quantity" th:field="*{quantity}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">出售平台：</label>
                <div class="col-sm-8">
                    <input name="platform" th:field="*{platform}" class="form-control" type="text">
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">总盈利：</label>
                <div class="col-sm-8">
                    <input name="totalProfit" th:field="*{totalProfit}" class="form-control" type="text">
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">创建时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="createdTime" th:value="${#dates.format(csSalesRecord.createdTime, 'yyyy-MM-dd')}"
                               class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">更新时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="updatedTime" th:value="${#dates.format(csSalesRecord.updatedTime, 'yyyy-MM-dd')}"
                               class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:insert="include :: select2-js"/>
<script th:inline="javascript">
    var prefix = ctx + "system/sales";
    $("#form-record-edit").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            let $form = $('#form-record-edit');
            // 获取表单数据并修改 price
            let formData = $form.serializeArray();
            let postData = {};

            // 将表单数据转换为对象
            formData.forEach(item => {
                postData[item.name] = item.value;
            });
            // 将 price 字段的值乘以 100
            postData.sellPrice = Math.round(parseFloat(postData.sellPrice) * 100);
            postData.sellCostPrice = Math.round(parseFloat(postData.sellCostPrice) * 100);
            postData.totalProfit = Math.round(parseFloat(postData.totalProfit) * 100);
            $.operate.save(prefix + "/edit", postData);
        }
    }

    $("input[name='createdTime']").datetimepicker({
        format: "yyyy-mm-dd HH:mm:ss",
        minView: 0,
        autoclose: true
    });

    $("input[name='updatedTime']").datetimepicker({
        format: "yyyy-mm-dd HH:mm:ss",
        minView: 0,
        autoclose: true
    });

    $(document).ready(function () {
        var sellPriceInput = $('input[name="sellPrice"]');
        var sellCostPriceInput = $('input[name="sellCostPrice"]');
        var totalProfitInput = $('input[name="totalProfit"]');
        var sellPriceValue = sellPriceInput.val();
        var sellCostPriceValue = sellCostPriceInput.val();
        var totalProfitValue = totalProfitInput.val();

        if ($('select[name="platform"]').val() === '4') {
            sellPriceInput.val((parseFloat(sellPriceValue) * 0.8 / 100).toFixed(2));
            sellCostPriceInput.val((parseFloat(sellCostPriceValue) * 0.8 / 100).toFixed(2));
            totalProfitInput.val((parseFloat(totalProfitValue) * 0.8 / 100).toFixed(2));
        } else {
            sellPriceInput.val((parseFloat(sellPriceValue) / 100).toFixed(2));
            sellCostPriceInput.val((parseFloat(sellCostPriceValue) / 100).toFixed(2));
            totalProfitInput.val((parseFloat(totalProfitValue) / 100).toFixed(2));
        }

        // 从隐藏字段获取初始值
        var initialName = $('#initialNameValue').val();
        var initialMarketHashName = $('#initialMarketHashNameValue').val();

        // 初始化 select2
        var $nameSelect = $('select[name="marketHashName"]').select2({
            placeholder: "请输入物品名称关键词", // 占位符
            allowClear: false,
            width: '100%',    // 宽度
            ajax: {
                url: '/system/name/list', // 你的后端搜索接口
                dataType: 'json',
                type: "post",
                delay: 250, // 延迟毫秒数，减少请求频率
                data: function (params) {
                    // 发送到服务器的参数
                    return {
                        name: params.term.split('').join('%') // 用户输入的文本在 `params.term` 中
                    };
                },
                processResults: function (data) {
                    // 处理后端返回的数据，转换成 Select2 期望的格式
                    // 假设你的后端返回格式为 { code:200, data: [{id:1, name:'物品A'}, ...] }
                    if (data.code === 0) {
                        var results = $.map(data.rows, function (item) {
                            return {
                                id: item.marketHashName,     // 选项的实际值（通常用于表单提交）
                                text: item.name     // 选项的显示文本
                            }
                        });
                        return {
                            results: results
                        };
                    } else {
                        return {results: []};
                    }
                },
                cache: true
            },
            minimumInputLength: 1 // 开始搜索前所需的最小字符数
        });

        if (initialName) {
            // 设置选中值
            var option = new Option(initialName, initialMarketHashName, true, true);
            $nameSelect.append(option).trigger('change');
        }
    });
</script>
</body>
</html>